/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.invoice.busines.dto;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

/**
 *
 * @author laura
 */
@FacesConverter(value = "clienteDTOConverter", forClass=ClienteDTO.class )
public class ClienteDTOConverter implements Converter {
@Override
public Object getAsObject(FacesContext arg0, UIComponent uiComponent, String value) {
    ClienteDTO result = new ClienteDTO();
    if(value != null && value.trim().length() > 0) {
            try {
                if(uiComponent.getAttributes().containsKey(value)){
                    result = (ClienteDTO) uiComponent.getAttributes().get(value);
                }
            } catch(NumberFormatException e) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid theme."));
            }
    }
    return result;        
}

@Override
public String getAsString(FacesContext arg0, UIComponent uiComponent, Object value) {
    String result = new String();
    if(value != null) {
            if (value instanceof ClienteDTO && ((ClienteDTO)value).getIdCliente()!= null) {
                ClienteDTO clienteDTO = (ClienteDTO) value;
                uiComponent.getAttributes().put(clienteDTO.getIdCliente().toString(), clienteDTO);
                result = clienteDTO.getIdCliente().toString();
            }
    }
    return result;
}
}